function [IBUSY, SUCCESS, FAIL, error]=solveChannel(vA,mB,CW)
%
%    Function to solve the embeded Markov Chain steady-state probability valance equations that
%  describes the Contention Acces Period (CAP) of the Channel using IEEE 802.15.4
%    Inputs:
%      -vA:    alpha vector -> probability for transitions 
%              Busy/Idle -> Busy/Idle²-> ... ->Busy/Idle^{CW_m-1} -> Idle^{CW_m}
%      -mB:    beta matrix -> probability for transitions Busy_x/Idle to SUCCES_{nx}
%      -CW_w:  Maximum Contention Window
%
%    Outputs: 
%      -IBUSY: long term proportion of transitions into state Busy/Idle_x
%      -S:     long term proportion of transitions into state SUCCES_nx
%      -FAIL:  long term proportion of transitions into state FAILURE
%      -error: one state has prob < 0 or > 1
%
%  Joaquín Recas-Piorno, December 2013
%  recas@ucm.es
%


  %PI_{BI1}, PI_{BIj}, PI_{Icw}, PI_{Snj}, PI_f
  A=[];
  
  %PI_{BI1} Eq(B.1)
  A(end+1, 1)=1;
  A(end, CW+1:(CW*2+1))=-ones(1,CW+1);
  %BUSY/IDLE^i Eq(B.2)
  for i=1:CW-1
    A(end+1,i)=-vA(i);
    A(end,i+1)=1;
  end
  if(CW==1)
    %Include alpha transition to IDLE state
    A(1,1)=1-vA;
  else
    %IDLE^CW equation Eq(B.3)
    A(end,i+1)=1-vA(i+1);
  end

  %SUCCESS equation Eq(B.4)
  for i=1:CW
    A(end+1,CW+i)=1;
    for j=i:CW
      A(end,j)=-mB(i,j);
    end
  end
  
  %Valance equation  Eq(B.5)
  A(end+1,:)=ones(1,CW*2+1);
    
  % Solve it using [0...0, 1] as the indpendient value
  %x=inv(A)*[zeros(1,CW*2),1]';
  x=A\[zeros(1,CW*2),1]';

  if(max(x)>1||min(x)<0)
    error=1;
  else
    error=0;
  end
  
  IBUSY=   x(1:CW)';
  SUCCESS= x(CW+1:end-1)';
  FAIL=    x(end);
  
end
